package org.zjx.action.route;

import org.zjx.action.Action;
import org.zjx.action.basic.DelayAction;
import org.zjx.action.basic.ScreenshotAction;
import org.zjx.action.game.ClickAddressAction;
import org.zjx.action.game.GameAction;
import org.zjx.action.game.TabAction;
import org.zjx.core.IWindow;
import org.zjx.entity.Address;
import org.zjx.service.ScreenService;
import org.zjx.service.impl.ScreenServiceImpl;

import java.awt.*;

public class RunningAction extends Action {
    protected static ScreenService screenService = new ScreenServiceImpl();
    private final Address targetAddress;

    public RunningAction(IWindow targetWindow, Address targetAddress) {
        super(targetWindow, false);
        this.targetAddress = targetAddress;
    }

    @Override
    protected void doExecute() throws Exception {

        while (!getAddressNow().equals(targetAddress)) {
            if (timeOut()){
                boolean isIndoor = checkIndoorStatus(targetWindow.getState().getGameState().getAddress());
                if (isIndoor){
                    ClickAddressAction clickAddressAction = new ClickAddressAction(targetWindow,targetAddress);
                    clickAddressAction.execute();
                    new DelayAction(targetWindow,1500);
                }else {
                    TabAction tabAction = new TabAction(targetWindow,targetAddress.getCity(),new Point(targetAddress.getX(),targetAddress.getY()));
                    tabAction.execute();
                }
            }
            new DelayAction(targetWindow,500);
        }
    }

    private boolean timeOut(){
        long before = stateManager.getGameState().getRecordAddressTime();
        return System.currentTimeMillis() - before > 3000;
    }

    public Address getAddressNow() {
        new ScreenshotAction(targetWindow).execute();
        new GameAction(targetWindow).execute();
        return targetWindow.getState().getGameState().getAddress();
    }
    private boolean checkIndoorStatus(Address address) {
        return screenService.isRoom(address.getCity());
    }

}